package com.surelution.lansao

class AddressVerifyController {

    def index = {
		def serverName = request.getServerName()
		def partner = Partner.findByDomainName(serverName)
		def orderStatus = OrderStatus.findByKey("ADDRESS_NOT_VERIFIED")
		List<Order> orders = Order.findAllByPartnerAndStatus(partner, orderStatus)
		List<Member> members = orders.collect {
			it.member
		}
		def cri = MemberAddress.createCriteria()
		def notVerifiedAddresses = cri.list() {
			'in'('member', members)
			eq('verified', false)
		}
		['memberAddressInstanceList':notVerifiedAddresses]
	}
	
	def showVerify = {
        def memberAddressInstance = MemberAddress.get(params.id)
        if (!memberAddressInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'memberAddress.label', default: 'MemberAddress'), params.id])}"
            redirect(action: "list")
        }
        else {
            return [memberAddressInstance: memberAddressInstance]
        }
    }
	
	def verify = {
        def memberAddressInstance = MemberAddress.get(params.id)
        if (memberAddressInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (memberAddressInstance.version > version) {
                    
                    memberAddressInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'memberAddress.label', default: 'MemberAddress')] as Object[], "Another user has updated this MemberAddress while you were editing")
                    render(view: "edit", model: [memberAddressInstance: memberAddressInstance])
                    return
                }
            }
//            memberAddressInstance.properties = params
			memberAddressInstance.lastDelivery = true
			memberAddressInstance.verified = true
            if (!memberAddressInstance.hasErrors() && memberAddressInstance.save(flush: true)) {
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'memberAddress.label', default: 'MemberAddress'), memberAddressInstance.id])}"
				def member = memberAddressInstance.member
				def waitingFors = WaitingFor.findAllByMember(member)
				if(waitingFors) {
					waitingFors.each {
						it.finished = true
						it.save(flush:true)
					}
				}
                redirect(action: "show", id: memberAddressInstance.id)
            }
            else {
                render(view: "edit", model: [memberAddressInstance: memberAddressInstance])
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'memberAddress.label', default: 'MemberAddress'), params.id])}"
            redirect(action: "list")
        }
    }
}
